//
//  OKViewController.swift
//  Community
//
//  Created by JKSD on 2019/8/5.
//  Copyright © 2019 ZKJ. All rights reserved.
//

import UIKit
import SwiftyJSON
import Alamofire

class SWPTOK2ViewController: UIViewController {
    
    
    let tableView = UITableView()
    var source: [String] = []
    


    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "查询结果"
        
        self.tableView.frame = CGRect (x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT - AllTopNavHeight)
        self.tableView.delegate = self
        self.tableView.dataSource = self
        self.tableView.separatorStyle = UITableViewCell.SeparatorStyle.none
        self.tableView.register(SWPTGarbageListCell.nib(), forCellReuseIdentifier: SWPTGarbageListCell.identifier)
        self.tableView.backgroundColor = .groupTableViewBackground
        self.view.addSubview(self.tableView)
        
    }
    
    @objc func backAct() {
        self.navigationController?.popViewController(animated: true)
    }
    
    
    open func searchImgy(img:UIImage)  {
        
         LYProgressHUD.showLoading("")
        let imgData = img.compress(withMaxLength: 3 * 1024 * 1024 )
        let charactersToEscape = "?!@#$^&%*+,:;='\"`<>()[]{}/\\| ";
        let allowedCharacters = CharacterSet.init(charactersIn: charactersToEscape).inverted
        let imageBase64Str = imgData!.base64EncodedString(options: Data.Base64EncodingOptions.lineLength64Characters).addingPercentEncoding(withAllowedCharacters: allowedCharacters)
        let access_token = UserDefaults.standard.value(forKey: "access_token")
        let url = "https://aip.baidubce.com/rest/2.0/image-classify/v2/advanced_general?access_token=\(String(describing: access_token))"
        
        var request = URLRequest(url: URL(string: url)!)
        request.timeoutInterval = 8
        request.httpMethod = HTTPMethod.post.rawValue
        request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField:"Content-Type")
        request.setValue("application/json", forHTTPHeaderField: "Accept")
        let data = "image=" + imageBase64Str!
        request.httpBody = data.data(using: .utf8)
        
        Alamofire.request(request).responseJSON { (response) in
             LYProgressHUD.hide()
            switch response.result{
            case .success:
                if let value = response.result.value as? [String:AnyObject]{
                    let results = JSON.init(value)["result"].arrayValue
                    self.source = results.map({ (item) -> String in
                       return item["keyword"].stringValue
                    })
                    self.tableView.reloadData()
                }else{
                    LYProgressHUD.showMessage("未识别到物体，请重试")
                }
                
            case .failure( _):
                LYProgressHUD.showMessage("网络错误！")
            }
        }
    }
}
extension SWPTOK2ViewController: UITableViewDelegate,UITableViewDataSource {
   
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        return self.source.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: SWPTGarbageListCell.identifier) as! SWPTGarbageListCell
        if indexPath.row % 2 == 0 {
            cell.bgView.backgroundColor = UIColor.groupTableViewBackground
            cell.backgroundColor = .groupTableViewBackground
        }else {
            cell.bgView.backgroundColor = UIColor.white
            cell.backgroundColor = .white
        }
        
        cell.selectionStyle = .none
        cell.name.text = self.source[indexPath.row]
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        return 44
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let str = self.source[indexPath.row]
        let ok = SWPTOKViewController()
        ok.searchKey(keyWord: str)
        self.navigationController?.pushViewController(ok, animated: true)
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
}
